<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-4xl mx-auto px-4">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-2">作业提交</h1>
        <p class="text-gray-600">在此页面查看作业要求并提交您的作业</p>
      </div>

      <!-- 作业选择区域 -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">选择作业</h2>
        <div class="flex flex-wrap gap-4 items-center">
          <div class="flex items-center gap-2">
            <label class="text-sm text-gray-600">班级:</label>
            <select 
              v-model="selectedClassId" 
              @change="loadHomeworkList"
              class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">请选择班级</option>
              <option v-for="cls in classes" :key="cls.id" :value="cls.id">
                {{ cls.name }}
              </option>
            </select>
          </div>
          <div class="flex items-center gap-2">
            <label class="text-sm text-gray-600">作业:</label>
            <select 
              v-model="selectedHomeworkId" 
              @change="loadHomeworkDetail"
              :disabled="!selectedClassId || loadingHomework"
              class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
            >
              <option value="">请选择作业</option>
              <option v-for="homework in homeworkList" :key="homework.id" :value="homework.id">
                {{ homework.title }}
              </option>
            </select>
          </div>
        </div>
      </div>

      <!-- 作业详情显示 -->
      <div v-if="selectedHomework" class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex justify-between items-start mb-4">
          <div>
            <h2 class="text-xl font-bold text-gray-900 mb-2">{{ selectedHomework.title }}</h2>
            <div class="text-sm text-gray-600 space-y-1">
              <p><span class="font-medium">班级:</span> {{ getClassName(selectedHomework.classId) }}</p>
              <p><span class="font-medium">截止时间:</span> {{ formatDate(selectedHomework.deadline) }}</p>
              <p><span class="font-medium">发布时间:</span> {{ formatDate(selectedHomework.createTime) }}</p>
            </div>
          </div>
          <span 
            :class="getStatusClass(selectedHomework.deadline)"
            class="px-3 py-1 text-sm rounded-full font-medium"
          >
            {{ getStatusText(selectedHomework.deadline) }}
          </span>
        </div>

        <div class="border-t pt-4">
          <h3 class="text-lg font-semibold text-gray-900 mb-3">作业要求:</h3>
          <div class="bg-gray-50 rounded-lg p-4">
            <pre class="whitespace-pre-wrap text-sm text-gray-700 font-mono">{{ selectedHomework.content }}</pre>
          </div>
        </div>
      </div>

      <!-- 作业提交区域 -->
      <div v-if="selectedHomework && !isExpired(selectedHomework.deadline)" class="bg-white rounded-lg shadow-sm p-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">提交作业</h2>
        
        <!-- 检查是否已提交 -->
        <div v-if="existingSubmission" class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
          <div class="flex items-start gap-3">
            <svg class="w-5 h-5 text-blue-600 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
            </svg>
            <div>
              <h4 class="text-blue-800 font-medium">您已提交过此作业</h4>
              <p class="text-blue-700 text-sm mt-1">提交时间: {{ formatDate(existingSubmission.submitTime) }}</p>
              <p class="text-blue-700 text-sm">提交内容: {{ existingSubmission.content }}</p>
            </div>
          </div>
        </div>

        <form @submit.prevent="submitHomework" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">作业说明</label>
            <textarea 
              v-model="submissionForm.content"
              rows="4"
              required
              :disabled="submitting"
              class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
              placeholder="请简要说明您的作业完成情况..."
            ></textarea>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">上传文件</label>
            <div class="border-2 border-dashed border-gray-300 rounded-lg p-6">
              <div class="text-center">
                <svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48">
                  <path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                </svg>
                <div class="mt-4">
                  <label class="cursor-pointer">
                    <span class="mt-2 block text-sm font-medium text-gray-900">
                      点击上传文件或拖拽文件到此区域
                    </span>
                    <input 
                      ref="fileInput"
                      type="file" 
                      multiple 
                      @change="handleFileSelect"
                      :disabled="submitting"
                      class="sr-only"
                      accept=".pdf,.doc,.docx,.txt,.jpg,.jpeg,.png,.gif,.zip,.rar,.mp3,.mp4,.java,.py,.js,.html,.css"
                    />
                  </label>
                  <p class="mt-1 text-xs text-gray-500">
                    支持的文件类型: PDF, Word, 文本, 图片, 压缩包, 音视频, 代码文件等
                  </p>
                </div>
              </div>
            </div>

            <!-- 已选文件列表 -->
            <div v-if="selectedFiles.length > 0" class="mt-4 space-y-2">
              <h4 class="text-sm font-medium text-gray-700">已选择文件:</h4>
              <div class="space-y-2">
                <div 
                  v-for="(file, index) in selectedFiles" 
                  :key="index"
                  class="flex items-center justify-between bg-gray-50 rounded-lg p-3"
                >
                  <div class="flex items-center gap-3">
                    <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    <div>
                      <p class="text-sm font-medium text-gray-900">{{ file.name }}</p>
                      <p class="text-xs text-gray-500">{{ formatFileSize(file.size) }}</p>
                    </div>
                  </div>
                  <button 
                    type="button"
                    @click="removeFile(index)"
                    :disabled="submitting"
                    class="text-red-500 hover:text-red-700 disabled:opacity-50"
                  >
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <div class="flex justify-end gap-3 pt-4">
            <button 
              type="button" 
              @click="clearForm"
              :disabled="submitting"
              class="px-4 py-2 text-gray-600 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors disabled:opacity-50"
            >
              清空
            </button>
            <button 
              type="submit"
              :disabled="submitting || (!submissionForm.content.trim() && selectedFiles.length === 0)"
              class="px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ submitting ? '提交中...' : '提交作业' }}
            </button>
          </div>
        </form>
      </div>

      <!-- 作业已过期提示 -->
      <div v-else-if="selectedHomework && isExpired(selectedHomework.deadline)" class="bg-red-50 border border-red-200 rounded-lg p-6">
        <div class="flex items-center gap-3">
          <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
          <div>
            <h3 class="text-red-800 font-medium">作业已过期</h3>
            <p class="text-red-700 text-sm mt-1">
              该作业的截止时间是 {{ formatDate(selectedHomework.deadline) }}，现在已无法提交。
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { homeworkAPI } from '../api/homework.js'
import { classAPI } from '../api/class.js'

// 响应式数据
const loadingHomework = ref(false)
const submitting = ref(false)
const classes = ref([])
const homeworkList = ref([])
const selectedClassId = ref('')
const selectedHomeworkId = ref('')
const selectedHomework = ref(null)
const existingSubmission = ref(null)
const selectedFiles = ref([])

// 表单数据
const submissionForm = ref({
  content: '',
  userId: '2025048' // 临时硬编码，实际应从登录用户获取
})

// 文件输入引用
const fileInput = ref(null)

// 获取班级列表
const loadClasses = async () => {
  try {
    // 使用模拟数据，因为班级API可能还未实现
    classes.value = [
      {
        id: '99ce2e9e016c4196ab2103ec7722e1b9',
        name: 'cyzy89 - Java开发班',
        code: '464786'
      }
    ]
  } catch (error) {
    console.error('加载班级列表失败:', error)
  }
}

// 获取作业列表
const loadHomeworkList = async () => {
  if (!selectedClassId.value) {
    homeworkList.value = []
    return
  }

  loadingHomework.value = true
  try {
    // 调用真实的后端API获取指定班级的作业
    const response = await homeworkAPI.getHomeworkByClassId(selectedClassId.value)
    
    if (response.code === 200) {
      // 处理分页数据或直接数组数据
      homeworkList.value = response.data.content || response.data || []
      console.log('成功加载班级作业列表:', homeworkList.value.length, '条')
    } else {
      console.error('加载作业列表失败:', response.message)
      homeworkList.value = []
    }
  } catch (error) {
    console.error('加载作业列表失败:', error)
    homeworkList.value = []
    
    // 如果API调用失败，显示错误信息
    if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error')) {
      console.warn('后端服务未启动，请先启动homework-service')
    }
  } finally {
    loadingHomework.value = false
  }
}

// 获取作业详情
const loadHomeworkDetail = async () => {
  if (!selectedHomeworkId.value) {
    selectedHomework.value = null
    existingSubmission.value = null
    return
  }

  try {
    // 调用API获取作业详情
    const response = await homeworkAPI.getHomeworkById(selectedHomeworkId.value)
    
    if (response.code === 200) {
      selectedHomework.value = response.data
      console.log('成功加载作业详情:', selectedHomework.value.title)
    } else {
      console.error('加载作业详情失败:', response.message)
      // 如果API失败，从本地列表中找
      selectedHomework.value = homeworkList.value.find(hw => hw.id == selectedHomeworkId.value)
    }
    
    // TODO: 检查是否已提交过 - 需要实现相关API
    // 暂时设置为null，表示未提交
    existingSubmission.value = null
    
  } catch (error) {
    console.error('加载作业详情失败:', error)
    // 如果API失败，从本地列表中找
    selectedHomework.value = homeworkList.value.find(hw => hw.id == selectedHomeworkId.value)
    existingSubmission.value = null
  }
}

// 获取班级名称
const getClassName = (classId) => {
  const cls = classes.value.find(c => c.id === classId)
  return cls ? cls.name : '未知班级'
}

// 获取状态样式类
const getStatusClass = (deadline) => {
  const now = new Date()
  const deadlineDate = new Date(deadline)
  
  if (deadlineDate > now) {
    return 'bg-green-100 text-green-800'
  } else {
    return 'bg-red-100 text-red-800'
  }
}

// 获取状态文本
const getStatusText = (deadline) => {
  const now = new Date()
  const deadlineDate = new Date(deadline)
  
  return deadlineDate > now ? '进行中' : '已过期'
}

// 检查是否过期
const isExpired = (deadline) => {
  return new Date(deadline) < new Date()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 处理文件选择
const handleFileSelect = (event) => {
  const files = Array.from(event.target.files)
  selectedFiles.value = [...selectedFiles.value, ...files]
}

// 移除文件
const removeFile = (index) => {
  selectedFiles.value.splice(index, 1)
}

// 清空表单
const clearForm = () => {
  submissionForm.value.content = ''
  selectedFiles.value = []
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 提交作业
const submitHomework = async () => {
  if (!selectedHomework.value) return
  
  submitting.value = true
  try {
    // 上传文件
    const uploadedFiles = []
    for (const file of selectedFiles.value) {
      try {
        const response = await homeworkAPI.uploadHomeworkFile(file, submissionForm.value.userId)
        if (response.code === 200) {
          uploadedFiles.push(response.data)
        }
      } catch (error) {
        console.error('文件上传失败:', file.name, error)
      }
    }

    // 提交作业
    const submitData = {
      content: submissionForm.value.content,
      userId: submissionForm.value.userId,
      files: uploadedFiles
    }

    console.log('提交作业数据:', submitData)
    // await homeworkAPI.submitHomework(selectedHomework.value.id, submitData)
    
    alert('作业提交成功！')
    clearForm()
    
    // 重新加载作业详情以显示提交状态
    await loadHomeworkDetail()
    
  } catch (error) {
    console.error('提交作业失败:', error)
    alert('提交失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 组件挂载
onMounted(() => {
  loadClasses()
})
</script>

<style scoped>
/* 文件拖拽样式 */
.file-drop-area {
  transition: all 0.3s ease;
}

.file-drop-area:hover {
  border-color: #3b82f6;
  background-color: #f8fafc;
}

/* 预格式化文本样式 */
pre {
  font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  line-height: 1.6;
}
</style>
